package com.lz.sports.vm.manager

import android.text.Editable
import android.text.TextUtils
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.comm.extension.toImgPart
import com.lz.comm.extension.toJsonRequestBody
import com.lz.comm.net.HttpManager
import com.lz.helper.idcard.IDCardHelper
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.library.extension.APP
import com.lz.library.extension.showToast
import com.lz.sports.R
import com.lz.sports.api.ExamineeAddApi
import com.lz.sports.api.UploadApi
import com.lz.sports.bean.ExamProject
import com.lz.sports.bean.Examinee
import com.lz.sports.core.ProjectManager
import com.lz.sports.core.SoundHelper
import com.lz.sports.db.ExamineeDatabase
import com.lz.sports.utils.ToastUtils
import com.lz.sports.utils.UploadUtils
import com.lz.sports.utils.toGson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import java.io.File

//考生新增
class ExamineeAddViewModel : BaseViewModel<BaseModel>(), IDCardHelper.IDCardCallback {

    //考试计划ID
    private val examPlanId = ProjectManager.examPlanId()

    //考区ID
    private val examAreaId = ProjectManager.examAreaId()

    //考点ID
    private val examSiteId = ProjectManager.examSiteId()

    //计划编号, 考区编号, 考点
    val examPlanCode = ProjectManager.examPlanCode()
    val examAreaCode = ProjectManager.examAreaCode()
    val examSiteCode = ProjectManager.examSiteCode()

    //头像
    private var photoPath: String? = null

    //输入框绑定的各种信息
    val num = MutableLiveData("")
    val name = MutableLiveData("")
    val idCard = MutableLiveData("")
    val school = MutableLiveData("")
    val grade = MutableLiveData("")
    val classes = MutableLiveData("")
    val sex = MutableLiveData(true)

    //填写是否完整
    val saveEnabled = MutableLiveData(false)
    private var numEnabled = false
    private var nameEnabled = false
    private var idCardEnabled = false
    private var schoolEnabled = false
    private var gradeEnabled = false
    private var classesEnabled = false

    //报考项目
    val examProject = MutableLiveData<ExamProject>()

    private val helper by lazy { IDCardHelper(APP, true, this) }

    private val soundHelper by lazy { SoundHelper() }

    override fun onCreate(owner: LifecycleOwner) {
        helper.start()
        examProject.value = ProjectManager.currentExamProject
        soundHelper.init(intArrayOf(com.lz.helper.R.raw.idcard_read, com.lz.helper.R.raw.idcard_success))
    }

    override fun onResume(owner: LifecycleOwner) {
        helper.restart()
        launch {
            delay(500)
            soundHelper.play(0)
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        helper.pause()
    }

    override fun onCleared() {
        super.onCleared()
        helper.quit()
        soundHelper.release()
    }

    fun afterNumChanged(editable: Editable) {
        numEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun afterNameChanged(editable: Editable) {
        nameEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun afterIdCardChanged(editable: Editable) {
        idCardEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun afterSchoolChanged(editable: Editable) {
        schoolEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun afterGradeChanged(editable: Editable) {
        gradeEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun afterClassesChanged(editable: Editable) {
        classesEnabled = !TextUtils.isEmpty(editable)
        checkSaveState()
    }

    fun photoPath(path: String) {
        photoPath = path
        checkSaveState()
    }

    fun save() {
        if (!isNetworkConnected(true)) return
        val project = examProject.value ?: return
        val photo = photoPath ?: return
        launch {
            val job = async(Dispatchers.Default) {
                ExamineeDatabase.get()
                    .hasExaminee(examPlanId, project.id, examAreaId, examSiteId, num.value!!, idCard.value!!)
            }
            if (job.await() > 0) {
                R.string.manager_repeat.showToast()
            } else {
                uploadExaminee(project, File(photo))
            }
        }
    }

    private fun checkSaveState() {
        saveEnabled.value = numEnabled && nameEnabled && idCardEnabled && schoolEnabled
                && gradeEnabled && classesEnabled && photoPath != null && examProject.value != null
    }

    fun selectProject(position: Int) {
        val selectExamProject = ProjectManager.examPlan?.examProjectList?.getOrNull(position)
        if (selectExamProject != null && selectExamProject != examProject.value) {
            this.examProject.value = selectExamProject
        }
    }

    override fun onCardResult(idCardInfo: IDCardInfo) {
        launch {
            soundHelper.play(1)
        }
        name.value = idCardInfo.name
        idCard.value = idCardInfo.num
        sex.value = idCardInfo.isMale()
        checkSaveState()
    }

    override fun onCardError(err: Int) {
    }

    //添加学生
    private fun uploadExaminee(project: ExamProject, photoFile: File) {
        val uploadApi = HttpManager.getService(UploadApi::class.java) ?: return
        launch {
            uploadApi.upload(photoFile.toImgPart("file"))
                .catch { updateDialogLoading(false) }
                .onStart { updateDialogLoading(true) }
                .collect {
                    if (it.isSuccess()) {
                        val examinee = Examinee(
                            name.value!!,
                            if (sex.value!!) 1 else 2,
                            idCard.value!!,
                            num.value!!,
                            school.value!!,
                            grade.value!!,
                            classes.value!!,
                            it.data!!,

                            ProjectManager.examPlanId(),
                            ProjectManager.examPlanCode(),
                            ProjectManager.examAreaId(),
                            ProjectManager.examAreaCode(),
                            ProjectManager.examSiteId(),
                            ProjectManager.examSiteCode(),

                            project.id
                        )
                        addExaminee(examinee, project)
                    } else {
                        updateDialogLoading(false)
                    }
                }
        }
    }

    //添加考生
    private fun addExaminee(examinee: Examinee, examProject: ExamProject) {
        val addApi = HttpManager.getService(ExamineeAddApi::class.java) ?: return
        launch {
            addApi.create(examinee.toGson().toJsonRequestBody())
                .catch { updateDialogLoading(false) }
                .onCompletion { updateDialogLoading(false) }
                .collect {
                    if (it.isSuccess()) {
                        examinee.id = it.data!!.id
                        //拷贝临时图片到对应文件夹下
                        val res = UploadUtils.copyFile(photoPath!!, examinee.examPhotoFile())
                        if (res) {
                            ExamineeDatabase.get().addExaminee(examinee, examProject)
                            LiveEventBus.get("ExamineeAdd_examinee", Examinee::class.java).post(examinee)
                            finish()
                        } else {
//                            LogUtils.i("copyFile err ${file.absolutePath}")
                        }
                    } else {
                        it.msg?.apply { ToastUtils.showMyToast(this, Toast.LENGTH_SHORT) }
                    }
                }
        }
    }
}